package org.thingsboard.server.controller;


import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.thingsboard.server.dao.tenantIp.TenantIpService;
import org.thingsboard.server.queue.util.TbCoreComponent;

import java.io.IOException;


@RestController
@TbCoreComponent
@RequestMapping("/api/tenant_ip")
@Slf4j
public class TenantIpController {

    @Autowired
    private TenantIpService tenantIpService;


    @GetMapping("/getIP/{tenantName}")
    private JSONObject getIpByUserName(@PathVariable("tenantName") String tenantName) {
        String ip = tenantIpService.getIpByLoginUser(tenantName);
        log.info("查询---->{}<----对应的ip,查询结果为--->{}", tenantName, ip);
        JSONObject result = new JSONObject();
        result.put("ip", StringUtils.isEmpty(ip) ? "未查询到ip" : ip);
        return result;
    }


    @GetMapping("/getCameras")
    public String getCamerasByTenant(@RequestParam("orgcode") String orgcode) {
        log.info("获取处理中心摄像头信息------>{}", orgcode);
        if (StringUtils.isEmpty(orgcode)) {
            throw new RuntimeException("租户信息不能为空");
        }
        String camerasByTenantName = tenantIpService.getCamerasByTenantName(orgcode);
        log.info("导入摄像头信息---->{}", camerasByTenantName);
        return camerasByTenantName;
    }

    @PostMapping("/getRtsp")
    @CrossOrigin
    private JSONObject getRtspByCameraId(@RequestBody JSONObject jsonObject) {
        String cameraId = String.valueOf(jsonObject.get("cameraId"));
        String orgCode = String.valueOf(jsonObject.get("orgcode"));
        if (StringUtils.isEmpty(orgCode)) {
            throw new RuntimeException("租户信息不能为空");
        }

        if (StringUtils.isEmpty(cameraId)) {
            throw new RuntimeException("摄像头id不能为空");
        }
        //根据租户id 获取 租户对应 ip
        String ip = tenantIpService.getIpByLoginUser(orgCode);
        //请求新一代接口
        log.info("请求获取拉流rtsp地址，摄像头id-------->{}------租户信息--->{}---ip--->{}",
                jsonObject, orgCode, ip);
        String url = "http://" + ip + ":30005/cameraStream/getCamerasUrl";
        try {
            // 创建HttpClient对象
            CloseableHttpClient httpClient = HttpClients.createDefault();

            // 创建HttpPost对象
            HttpPost httpPost = new HttpPost(url);

            // 设置请求头
            httpPost.setHeader("Content-Type", "application/json");
            // 构造请求体数据
            JSONObject requestBody = new JSONObject();
            requestBody.put("cameraId", cameraId);
            requestBody.put("minute", 0);
            // 设置请求体
            StringEntity requestEntity = new StringEntity(JSONObject.toJSONString(requestBody));
            httpPost.setEntity(requestEntity);
            // 执行请求
            CloseableHttpResponse response = httpClient.execute(httpPost);
            // 获取响应内容
            HttpEntity entity = response.getEntity();
            String responseBody = EntityUtils.toString(entity);
            log.info("返回数据---->{}", responseBody);
            // 获取响应状态码
//            int statusCode = response.getStatusLine().getStatusCode();
            // 关闭响应
            response.close();
            // 关闭HttpClient
            httpClient.close();
            return JSONObject.parseObject(responseBody);
        } catch (IOException e) {
//            JSONObject jsonObject1 = new JSONObject();
//            jsonObject1.put("result", "rtsp://200.22.252.70:554/openUrl/GvybHTq");
//            return jsonObject1;
            throw new RuntimeException("获取拉流地址失败");
        }
    }
}
